package com.yixin.hospital.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;

public class DateUtil {

    public static final String YMN = "yyyyMMdd";
    public static final String YMD = "yyyy-MM-dd";

    /**
     * 计算时间相差年月日
     */
    public static String diffTime(Date time) {
        LocalDate startDate = LocalDate.now();
        LocalDate endDate = time.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        Period period = Period.between(startDate, endDate);
        int years = period.getYears();
        int months = period.getMonths();
        int days = period.getDays();
        return years + "年" + months + "月" + days + "天";
    }

    /**
     * 计算时间相差年
     */
    public static int getAge(Date birthDay) {
        LocalDate startDate = LocalDate.now();
        LocalDate endDate = birthDay.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        Period period = Period.between(startDate, endDate);
        return period.getYears();
    }

    /**
     * 计算时间相差天
     */
    public static int getDiffDays(LocalDate startDate, LocalDate endDate) {
        Period period = Period.between(startDate, endDate);
        return period.getDays();
    }

    /**
     * data to string
     */
    public static String dateToString(LocalDateTime dateTime, String format) {
        DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern(format);
        return myFormatObj.format(dateTime);
    }

    public static Date stringToDate(String dateStr, String format) {
        if (dateStr == null || dateStr.trim().isEmpty()) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        sdf.setLenient(false); // 严格模式
        try {
            return sdf.parse(dateStr.trim());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    public static String toChineseDate(Integer minutes) {
        String resultTime = minutes + "分钟";
        if (minutes > 60*24) {
            resultTime = "1天以上";
        } else if (minutes>60) {
            int hour = minutes / 60;
            int minute = minutes - hour*60;
            resultTime = hour + "小时" + minute + "分钟";
        }
        return resultTime;
    }
}
